package order

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"math"
	"net/http"
	"os"
	"strconv"
	"strings"
	"trade/logger"
)

type HeyuediRatio struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data []struct {
		ExchangeIcon      string `json:"exchange_icon"`
		Symbol            string `json:"symbol"`
		Price             string `json:"price"`
		PricePercent      string `json:"pricePercent"`
		PricePercentColor string `json:"pricePercentColor"`
		LongPercent       string `json:"longPercent"`
		ShortPercent      string `json:"shortPercent"`
	} `json:"data"`
}

func (this *HeyuediRatio) GetQuanWangSuggest() (danbian bool, direct string) {
	quanW := this.Data[len(this.Data)-1:][0]
	buyRatio, _ := strconv.ParseFloat(quanW.LongPercent, 64)
	sellRatio, _ := strconv.ParseFloat(quanW.ShortPercent, 64)
	direct = "buy"
	if buyRatio < sellRatio {
		direct = "sell"
	}
	danbian = false
	//很大的单边行情
	if math.Abs(buyRatio-sellRatio) > 15 {
		danbian = true
	}
	return
}

func (this *HeyuediRatio) GetProfit() float64 {
	quanW := this.Data[len(this.Data)-1:][0]
	buyRatio, _ := strconv.ParseFloat(quanW.LongPercent, 64)
	sellRatio, _ := strconv.ParseFloat(quanW.ShortPercent, 64)
	if buyRatio < sellRatio {
		return sellRatio/buyRatio - 1
	}
	return buyRatio/sellRatio - 1
}

func GetRatio(symbol, period string) (HeyuediRatio, error) {
	symbol = strings.ToLower(symbol)
	url := fmt.Sprintf("http://wx.heyuedi.com/alarm/trade/symbolRatio?symbol=%s&period=%s", symbol, period)
	b, err := HttpGet(url)
	if err != nil {
		return HeyuediRatio{}, err
	}
	var r HeyuediRatio
	_ = json.Unmarshal(b, &r)
	if r.Code != 0 {
		return HeyuediRatio{}, errors.New(r.Msg)
	}
	return r, nil
}

func HttpGet(url string) ([]byte, error) {
	client := &http.Client{}
	reqest, err := http.NewRequest("GET", url, nil) //建立一个请求
	if err != nil {
		fmt.Println("Fatal error ", err.Error())
		os.Exit(0)
	}
	//Add 头协议
	reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	reqest.Header.Add("Accept-Language", "ja,zh-CN;q=0.8,zh;q=0.6")
	reqest.Header.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")
	response, err := client.Do(reqest) //提交
	defer func() {
		_ = response.Body.Close()
	}()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		// handle error
		logger.Log.Error(err)
		return nil, err
	}
	return body, nil

}
